package com.athl.gulimall.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.athl.common.valid.SaveValid;
import com.athl.common.valid.UpdateStatus;
import com.athl.common.valid.UpdateVaild;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.athl.gulimall.product.entity.BrandEntity;
import com.athl.gulimall.product.service.BrandService;
import com.athl.common.utils.PageUtils;
import com.athl.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author yixin
 * @email sunlightcs@gmail.com
 * @date 2022-05-14 14:49:27
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     * @Valid 表示该实体类需要校验
     * BindResult 校验的结果
     * @Validated 分组校验
     */
    @RequestMapping("/save")
    public R save(@Validated(value = SaveValid.class) @RequestBody BrandEntity brand/*, BindingResult result*/){
//        放到统一异常处理里了
//        if (result.hasErrors()){
//            Map<String,String> map = new HashMap<>();
//            // 1.获取校验的错误结果
//            result.getFieldErrors().forEach((item)->{
//                // 获取到错误提示消息
//                String message = item.getDefaultMessage();
//                // 获取错误属性的名字
//                String field = item.getField();
//                map.put(field,message);
//            });
//
//            return R.error(400,"提交的数据不合法").put("data",map);
//        }else {
//
//        }
        brandService.save(brand);
        return R.ok();
    }

    /**
     * 修改更新
     */
    @RequestMapping("/update")
    public R update(@Validated(value = UpdateVaild.class) @RequestBody BrandEntity brand){
		brandService.updateDetail(brand);

        return R.ok();
    }
    /**
     * 修改状态
     */
    @PostMapping("/update/status")
    public R updateStatus(@Validated(value = UpdateStatus.class) @RequestBody BrandEntity brand) {
        brandService.updateById(brand);
        return R.ok();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
